package org.koyad.portal.context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import org.koyad.portal.exceptions.ErrorCodes;
import org.koyad.portal.exceptions.FrameworkException;

public class PistonRequest implements HttpServletRequest {

	private HttpServletRequest _req = null;
	private String _requestTileId = null;
	private List<String> _tileIds = new ArrayList<String>();
	private HttpSession _session = null;

	public PistonRequest(HttpServletRequest req, String tileId) {
		_req = req;
		_requestTileId = tileId;
	}
	
	public String getReqTileId() {
		return _requestTileId;
	}

	private Map<String, Object> getTileMap() {
		Map<String, Object> map = (Map<String, Object>)_req.getAttribute(getCurrentTileId());
		if(null == map) {
			map = new HashMap<String, Object>();
			_req.setAttribute(getCurrentTileId(), map);
			_tileIds.add(getCurrentTileId());
		}
		return map;
	}
	
	private String getCurrentTileId() {
		return PistonContext.getContext().getViewRoot().getCurrentTileId();
	}

	@Override
	public AsyncContext getAsyncContext() {
		return _req.getAsyncContext();
	}

	@Override
	public Object getAttribute(String name) {
		Object value = null;
		if (null == _requestTileId && null == getCurrentTileId()) {
			value =  _req.getAttribute(name);
		} else {
			value = getTileMap().get(name);
		}
		return value;
	}

	@Override
	public Enumeration<String> getAttributeNames() {
		Enumeration<String> value = Collections.enumeration(new HashSet<String>());
		if (null == _requestTileId && null == getCurrentTileId()) {
			value =  _req.getAttributeNames();
		} else {
			value = Collections.enumeration(getTileMap().keySet());
		}
		return value;
	}

	@Override
	public String getCharacterEncoding() {
		return _req.getCharacterEncoding();
	}

	@Override
	public int getContentLength() {
		return _req.getContentLength();
	}

	@Override
	public String getContentType() {
		return _req.getContentType();
	}

	@Override
	public DispatcherType getDispatcherType() {
		return _req.getDispatcherType();
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		return _req.getInputStream();
	}

	@Override
	public String getLocalAddr() {
		return _req.getLocalAddr();
	}

	@Override
	public String getLocalName() {
		return _req.getLocalName();
	}

	@Override
	public int getLocalPort() {
		return _req.getLocalPort();
	}

	@Override
	public Locale getLocale() {
		return _req.getLocale();
	}

	@Override
	public Enumeration<Locale> getLocales() {
		return _req.getLocales();
	}

	@Override
	public String getParameter(String name) {
		String value = null;
		if (null == _requestTileId && null == getCurrentTileId()) {
			value =  _req.getParameter(name);
		} else if (null == _requestTileId || getCurrentTileId().equals(_requestTileId)) {
			value = _req.getParameter(name);
		}
		return value;
	}

	@Override
	public Map<String, String[]> getParameterMap() {
		Map<String, String[]> value = null;
		if (null == _requestTileId && null == getCurrentTileId()) {
			value =  _req.getParameterMap();
		} else if (null == _requestTileId || getCurrentTileId().equals(_requestTileId)) {
			value = _req.getParameterMap();
		}
		return value;
	}

	@Override
	public Enumeration<String> getParameterNames() {
		Enumeration<String> value = Collections.enumeration(new HashSet<String>());
		if (null == _requestTileId && null == getCurrentTileId()) {
			value =  _req.getParameterNames();
		} else if (null == _requestTileId || getCurrentTileId().equals(_requestTileId)) {
			value = _req.getParameterNames();
		}
		return value;
	}

	@Override
	public String[] getParameterValues(String arg0) {
		String[] value = null;
		if (null == _requestTileId && null == getCurrentTileId()) {
			value =  _req.getParameterValues(arg0);
		} else if (null == _requestTileId || getCurrentTileId().equals(_requestTileId)) {
			value = _req.getParameterValues(arg0);
		}
		return value;
	}

	@Override
	public String getProtocol() {
		return _req.getProtocol();
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return _req.getReader();
	}

	@Override
	public String getRealPath(String arg0) {
		return _req.getRealPath(arg0);
	}

	@Override
	public String getRemoteAddr() {
		return _req.getRemoteAddr();
	}

	@Override
	public String getRemoteHost() {
		return _req.getRemoteHost();
	}

	@Override
	public int getRemotePort() {
		return _req.getRemotePort();
	}

	@Override
	public RequestDispatcher getRequestDispatcher(String arg0) {
		return _req.getRequestDispatcher(arg0);
	}

	@Override
	public String getScheme() {
		return _req.getScheme();
	}

	@Override
	public String getServerName() {
		return _req.getServerName();
	}

	@Override
	public int getServerPort() {
		return _req.getServerPort();
	}

	@Override
	public ServletContext getServletContext() {
		return _req.getServletContext();
	}

	@Override
	public boolean isAsyncStarted() {
		return _req.isAsyncStarted();
	}

	@Override
	public boolean isAsyncSupported() {
		return _req.isAsyncSupported();
	}

	@Override
	public boolean isSecure() {
		return _req.isSecure();
	}

	@Override
	public void removeAttribute(String arg0) {
		if (null == _requestTileId && null == getCurrentTileId()) {
			if(!_tileIds.contains(arg0)) {
				_req.removeAttribute(arg0);
			} else {
				throw new FrameworkException(ErrorCodes.FWKPR002);
			}
		} else {
			getTileMap().remove(arg0);
		}
	}

	@Override
	public void setAttribute(String arg0, Object arg1) {
		if (null == _requestTileId && null == getCurrentTileId()) {
			if(!_tileIds.contains(arg0)) {
				_req.setAttribute(arg0, arg1);
			} else {
				throw new FrameworkException(ErrorCodes.FWKPR001);
			}
		} else {
			getTileMap().put(arg0, arg1);
		}
	}

	@Override
	public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException {
		_req.setCharacterEncoding(arg0);
	}

	@Override
	public AsyncContext startAsync() {
		return _req.startAsync();
	}

	@Override
	public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) {
		return _req.startAsync(arg0, arg1);
	}

	@Override
	public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException {
		return _req.authenticate(arg0);
	}

	@Override
	public String getAuthType() {
		return _req.getAuthType();
	}

	@Override
	public String getContextPath() {
		return _req.getContextPath();
	}

	@Override
	public Cookie[] getCookies() {
		return _req.getCookies();
	}

	@Override
	public long getDateHeader(String arg0) {
		return _req.getDateHeader(arg0);
	}

	@Override
	public String getHeader(String arg0) {
		return _req.getHeader(arg0);
	}

	@Override
	public Enumeration<String> getHeaderNames() {
		return _req.getHeaderNames();
	}

	@Override
	public Enumeration<String> getHeaders(String arg0) {
		return _req.getHeaders(arg0);
	}

	@Override
	public int getIntHeader(String arg0) {
		return _req.getIntHeader(arg0);
	}

	@Override
	public String getMethod() {
		return _req.getMethod();
	}

	@Override
	public Part getPart(String arg0) throws IOException, IllegalStateException, ServletException {
		return _req.getPart(arg0);
	}

	@Override
	public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException {
		return _req.getParts();
	}

	@Override
	public String getPathInfo() {
		return _req.getPathInfo();
	}

	@Override
	public String getPathTranslated() {
		return _req.getPathTranslated();
	}

	@Override
	public String getQueryString() {
		String value = null;
		if (null == _requestTileId && null == getCurrentTileId()) {
			value =  _req.getQueryString();
		} else if (null == _requestTileId || getCurrentTileId().equals(_requestTileId)) {
			value = _req.getQueryString();
		}
		return value;
	}

	@Override
	public String getRemoteUser() {
		return _req.getRemoteUser();
	}

	@Override
	public String getRequestURI() {
		if (null != getCurrentTileId()) {
			return null;
		}
		return _req.getRequestURI();
	}

	@Override
	public StringBuffer getRequestURL() {
		if (null != getCurrentTileId()) {
			return null;
		}
		return _req.getRequestURL();
	}

	@Override
	public String getRequestedSessionId() {
		return _req.getRequestedSessionId();
	}

	@Override
	public String getServletPath() {
		if (null != getCurrentTileId()) {
			return null;
		}
		return _req.getServletPath();
	}

	@Override
	public HttpSession getSession() {
		if(null == _session && null != _req.getSession()) {
			_session = new PistonSession(_req.getSession(), _requestTileId);
		}
		return _session;
	}

	@Override
	public HttpSession getSession(boolean arg0) {
		if(null != _req.getSession(arg0) && null == _session) {
			_session = new PistonSession(_req.getSession(arg0), _requestTileId);
		}
		return _session;
	}

	@Override
	public Principal getUserPrincipal() {
		return _req.getUserPrincipal();
	}

	@Override
	public boolean isRequestedSessionIdFromCookie() {
		return _req.isRequestedSessionIdFromCookie();
	}

	@Override
	public boolean isRequestedSessionIdFromURL() {
		return _req.isRequestedSessionIdFromURL();
	}

	@Override
	public boolean isRequestedSessionIdFromUrl() {
		return _req.isRequestedSessionIdFromUrl();
	}

	@Override
	public boolean isRequestedSessionIdValid() {
		return _req.isRequestedSessionIdValid();
	}

	@Override
	public boolean isUserInRole(String arg0) {
		return _req.isUserInRole(arg0);
	}

	@Override
	public void login(String arg0, String arg1) throws ServletException {
		_req.login(arg0, arg1);

	}

	@Override
	public void logout() throws ServletException {
		_req.logout();
	}

}
